package com.tianji.promotion.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tianji.common.domain.dto.PageDTO;
import com.tianji.promotion.constants.PromotionConstants;
import com.tianji.promotion.domain.po.Coupon;
import com.tianji.promotion.domain.po.ExchangeCode;
import com.tianji.promotion.domain.query.CodeQuery;
import com.tianji.promotion.domain.vo.CodePageVO;
import com.tianji.promotion.mapper.ExchangeCodeMapper;
import com.tianji.promotion.service.IExchangeCodeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.promotion.utils.CodeUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 兑换码 服务实现类
 * </p>
 *
 * @author hrz
 * @since 2025-09-01
 */
@Service
@RequiredArgsConstructor
public class ExchangeCodeServiceImpl extends ServiceImpl<ExchangeCodeMapper, ExchangeCode> implements IExchangeCodeService {

    private final RedisTemplate redisTemplate;

    @Override
    @Async("promotionExec")
    public void generateCode(Coupon coupon) {
        //异步生成兑换码
        //1.生成自增id - 使用redis的incrby指令
        String key = PromotionConstants.COUPON_CODE_SERIAL_KEY;
        Integer totalNum = coupon.getTotalNum();
        Long increment = redisTemplate.opsForValue().increment(key, totalNum);
        if (increment == null) {
            return;
        }
        //2.循环生成兑换码
        List<ExchangeCode> exchangeCodeList = new ArrayList<>();
        for (int begin = increment.intValue() - totalNum + 1;
             begin <= increment; begin++) {
            //生成兑换码
            String code= CodeUtil.generateCode(begin, coupon.getId());
            //封装到po类
            ExchangeCode exchangeCode = new ExchangeCode();
            exchangeCode.setCode(code);
            exchangeCode.setExpiredTime(coupon.getIssueEndTime());
            exchangeCode.setId(begin);
            exchangeCode.setExchangeTargetId(coupon.getId());
            exchangeCodeList.add(exchangeCode);
        }
        //3.将兑换码批量保存到数据库
        boolean b = this.saveBatch(exchangeCodeList);

        //4.在redis中保存优惠券的最大兑换码数
        Boolean add = redisTemplate.opsForZSet()
                .add(PromotionConstants.COUPON_RANGE_KEY,
                        coupon.getId(), increment);
    }

    @Override
    public PageDTO<CodePageVO> queryPage(CodeQuery query) {
        Integer status = query.getStatus();
        Long couponId = query.getCouponId();
        //1.分页查询
        Page<ExchangeCode> page = this.lambdaQuery()
                .eq(ExchangeCode::getStatus, status)
                .eq(ExchangeCode::getExchangeTargetId, couponId)
                .page(query.toMpPageDefaultSortByCreateTimeDesc());
        if(page == null){
            return PageDTO.empty(0L,0L);
        }
        List<ExchangeCode> records = page.getRecords();
        //2.转换成VO
        List<CodePageVO> vos = new ArrayList<>();
        for (ExchangeCode record : records) {
            CodePageVO vo = new CodePageVO();
            BeanUtil.copyProperties(record, vo);
            vos.add(vo);
        }
        return PageDTO.of(page,vos);
    }
}
